package com.leetCode.ListNodeDemo;


import java.util.ArrayList;
import java.util.List;

public class TrainingPlanDemo {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(2,new ListNode(4,new ListNode(7,new ListNode(8))));
        System.out.println(trainingPlan1(listNode,1).val);
    }

    /**
     * 给定一个头节点为 head 的链表用于记录一系列核心肌群训练项目编号，请查找并返回倒数第 cnt 个训练项目编号。
     *
     *
     *
     * 示例 1：
     *
     * 输入：head = [2,4,7,8], cnt = 1
     * 输出：8
     *
     *
     * 提示：
     *
     * 1 <= head.length <= 100
     * 0 <= head[i] <= 100
     * 1 <= cnt <= head.length
     */
    public static ListNode trainingPlan(ListNode head, int cnt) {
        List<ListNode> list = new ArrayList<>();
        ListNode temp = head;
        while (temp != null){
            list.add(temp);
            temp = temp.next;
        }
        return list.get(list.size() - cnt);
    }

    /**
     * 使用双指针（根据指针间距判断）
     */
    public static ListNode trainingPlan1(ListNode head, int cnt) {
        //相差cnt位的指针
        ListNode first = head;
        ListNode last = head;
        while (cnt > 1){
            last = last.next;
            cnt--;
        }
        while (last != null){
            last = last.next;
            if (last == null){
                return first;
            }
            first = first.next;
        }
        return null;
    }
}
